package com.seeyon.ctp.rest.resources;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.seeyon.apps.nygj.util.*;
import com.seeyon.cap4.form.bean.FormBean;
import com.seeyon.cap4.form.bean.FormDataMasterBean;
import com.seeyon.cap4.form.service.CAP4FormManager;
import com.seeyon.ctp.common.AppContext;
import com.seeyon.ctp.common.filemanager.manager.AttachmentManager;
import com.seeyon.ctp.common.log.CtpLogFactory;
import com.seeyon.ctp.common.po.ctpenumnew.CtpEnumItem;
import org.apache.commons.logging.Log;

import javax.ws.rs.Consumes;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Path("jssdk")
@Consumes(MediaType.APPLICATION_JSON)
@Produces({MediaType.APPLICATION_JSON})
public class CustomFormDataStateResources extends BaseResource {
    private static final Log log = CtpLogFactory.getLog(CustomFormDataStateResources.class);
    private String localAddr = AppContext.getRawRequest().getLocalAddr();
    private String port = String.valueOf(AppContext.getRawRequest().getLocalPort());
    private static CAP4FormManager cap4FormManager = (CAP4FormManager) AppContext.getBean("cap4FormManager");
    private static final String fkUnFlowTemplateCode = AppContext.getSystemProperty("ndk.fkUnFlowTemplateCode");

    /**
     * 更新表单数据状态
     *
     * @param param 包含表单数据状态更新信息的Map
     * @return 返回操作结果的Response对象
     */
    @POST
    @Path("updateFormDataStateNew")
    public Response updateFormDataState(Map<String, Object> param) throws Exception {
        String dataJson = JSON.toJSONString(param);
        log.info("主数据平台调用接口入参json:" + dataJson);
//        ErrorKit.addLog("主数据平台调用接口入参json：" + dataJson, CustomFormDataStateResources.class.getName());
        JSONObject jsonObj = new JSONObject(param);
        String guid = "";
        String ythGuid = "";
        String F_YWLX = "";
        String CODE = "";
        StringBuilder stb = new StringBuilder();
        if (jsonObj.containsKey("data")) {
            JSONArray jsonArray = jsonObj.getJSONArray("data");
            if (jsonArray.size() > 0) {
                for (int i = 0; i < jsonArray.size(); i++) {
                    JSONObject jsonObject = jsonArray.getJSONObject(i);
                    guid = StrKit.str(jsonObject.get("srcGUID"));
                    ythGuid = StrKit.str(jsonObject.get("GUID"));
                    CODE = StrKit.str(jsonObject.get("CODE"));
                    stb.append(StrKit.str(jsonObject.get("MSG")));
                    F_YWLX = StrKit.str(jsonObject.get("F_YWLX"));
                }
            }
        } else {
            ythGuid = StrKit.str(jsonObj.get("GUID"));
            guid = StrKit.str(jsonObj.get("srcGUID"));
            F_YWLX = StrKit.str(jsonObj.get("F_YWLX"));
        }

        String opType = StrKit.str(jsonObj.get("opType"));
        Long memberId = null;
        String formCode = "";
        try {
            // 检查guid是否为空
            if ("".equals(guid)) {
                Map<String, Object> msgMap = MessageKit.errorMsg("1", "guid不能为空值", guid);
                FormCap4Kit.addLogs(memberId, "合同状态回调接口", formCode, "JKCGBS_E", dataJson, JSON.toJSONString(msgMap));
                return ok(JSON.toJSON(msgMap));
            }
            // 处理guid格式数据，更新表单状态
            if (guid.contains("_")) {
                String dataId = guid.split("_")[0];

                String templateCode = guid.split("_")[1];
                FormBean formBean = cap4FormManager.getFormByFormCode(templateCode);
                // 检查模版编码是否存在
                if (formBean == null) {
                    Map<String, Object> msgMap = MessageKit.errorMsg("1", "模版编码不存在，未找到对应的OA单据!", guid);
                    FormCap4Kit.addLogs(memberId, "合同状态回调接口", formCode, "JKCGBS_E", dataJson, JSON.toJSONString(msgMap));
                    return ok(JSON.toJSON(msgMap));
                }
                FormDataMasterBean formDataMasterBean = cap4FormManager.getDataMasterBeanById(Long.parseLong(dataId), formBean, null);
                if (formDataMasterBean == null) {
                    Map<String, Object> msgMap = MessageKit.errorMsg("1", "guid[" + guid + "]有误,系统中未找到该合同!", guid);
                    FormCap4Kit.addLogs(memberId, "合同状态回调接口", formCode, "JKCGBS_E", dataJson, JSON.toJSONString(msgMap));
                    return ok(JSON.toJSON(msgMap));
                }
                memberId = formDataMasterBean.getStartMemberId();
                formCode = StrKit.str(formDataMasterBean.getFieldValue(formDataMasterBean.getFormTable().getFieldBeanByDisplay("业务单据编号").getName()));
                boolean isFile = false;
                if ("BILL_SAVE".equals(opType) && "0".equals(CODE)) {
                    Map<String, String> fieldMap = formBean.getAllFieldNameMap();
                    for (Map.Entry<String, String> entry : fieldMap.entrySet()) {
                        String fieldValue = StrKit.str(entry.getValue());
                        if ("附件".equals(fieldValue)) {
                            isFile = true;
                        }
                    }
                    if (isFile) {
                        String SUB_REFERENCE = StrKit.str(formDataMasterBean.getFieldValue(formDataMasterBean.getFormTable().getFieldBeanByDisplay("附件").getName()));
                        if (!"".equals(SUB_REFERENCE)) {
                            AttachmentManager attachmentManager = (AttachmentManager) AppContext.getBean("attachmentManager");
                            List<Long> list = attachmentManager.getBySubReference(Long.parseLong(SUB_REFERENCE));
                            String ip = "http://" + localAddr + ":" + port;
                            FileKit.uploadFile(list, ythGuid, memberId, formCode, ip);
                        }
                    }
                }

                // 根据类型更新不同的字段值
                String czlx_fieldName = formDataMasterBean.getFormTable().getFieldBeanByDisplay("操作类型").getName();
                String fhxx_fieldName = formDataMasterBean.getFormTable().getFieldBeanByDisplay("返回信息").getName();
                List<String> fieldList = new ArrayList<String>();

                String orgCode = StrKit.str(formDataMasterBean.getFieldValue(formDataMasterBean.getFormTable().getFieldBeanByDisplay("组织机构编码").getName()));
                if ("FLOW_FINISH".equals(opType)) {
                    Map<String, String> fieldMap = formBean.getAllFieldNameMap();
                    String fieldName = "";
                    String formType = "";
                    boolean isJsd = false;
                    for (Map.Entry<String, String> entry : fieldMap.entrySet()) {
                        String fieldValue = StrKit.str(entry.getValue());
                        if ("凭证编号".equals(fieldValue)) {
                            isJsd = true;
                            fieldName = formDataMasterBean.getFormTable().getFieldBeanByDisplay("凭证编号").getName();
                        }
                        if ("合同编号".equals(fieldValue)) {
                            fieldName = formDataMasterBean.getFormTable().getFieldBeanByDisplay("合同编号").getName();
                        }
                    }
                    if (isJsd) {
                        formType = "jsd";
                    } else {
                        formType = "ht";
                    }
                    String htCode = HtKit.getHtCode(formType, memberId, formCode, ythGuid, F_YWLX, orgCode);
                    formDataMasterBean.addFieldValue(fieldName, htCode);
                    fieldList.add(fieldName);
                }
                CtpEnumItem ctpEnumItem = FormCap4Kit.getEnumByCode(opType);
                if (ctpEnumItem != null) {
                    formDataMasterBean.addFieldValue(czlx_fieldName, ctpEnumItem.getId());
                    fieldList.add(czlx_fieldName);
                }
                formDataMasterBean.addFieldValue(fhxx_fieldName, stb.toString());
                fieldList.add(fhxx_fieldName);
                fieldList.add(czlx_fieldName);

                // 保存或更新表单数据
                cap4FormManager.saveOrUpdateFormData(formDataMasterBean, formBean.getId(), true, fieldList);
                Map<String, Object> msgMap = MessageKit.errorMsg("0", "更新状态成功", guid);
                FormCap4Kit.addLogs(memberId, "合同状态回调接口", formCode, "JKCGBS_S", dataJson, JSON.toJSONString(msgMap));
                return ok(JSON.toJSON(msgMap));
            }
        } catch (Exception e) {
            log.error("更新表单状态失败", e);
            String errorMsg = "更新表单状态失败:" + e.getMessage();
            Map<String, Object> msgMap = MessageKit.errorMsg("1", errorMsg, guid);
            FormCap4Kit.addLogs(memberId, "合同状态回调接口", formCode, "JKCGBS_E", dataJson, JSON.toJSONString(msgMap));
            return ok(JSON.toJSON(msgMap));
        }
        return null;
    }


}